/*
   Copyright 2010 the original author or authors

   Licensed under the Apache License, Version 2.0 (the "License");
   you may not use this file except in compliance with the License.
   You may obtain a copy of the License at

       http://www.apache.org/licenses/LICENSE-2.0

   Unless required by applicable law or agreed to in writing, software
   distributed under the License is distributed on an "AS IS" BASIS,
   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   See the License for the specific language governing permissions and
   limitations under the License.
*/
package com.googlecode.flightreports.citydetails;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.List;

import com.googlecode.kohmori.reportgen.AbstractSQLSource;
import com.googlecode.kohmori.springmvc.DefaultReportParams;

import javax.xml.bind.JAXBElement;
import javax.xml.namespace.QName;


/* 
 * This class creates the report object and uses SQL to populate its values.
 */
@SuppressWarnings("restriction")
public class ReportSQL extends AbstractSQLSource {

   @Override
   public String getJAXBPackageList() {
      return "com.googlecode.flightreports.citydetails";
   }
   
   /**
    * Creates a report object
    * 
    * @param dbConn
    *           Connection object to run SQL
    * @return report instance, null if no report found
    */
   @Override
   public JAXBElement<?> createReportObject(Connection dbConn,
         DefaultReportParams reportParams) throws SQLException {
      ReportParams rP = (ReportParams) reportParams;
      CityDetailsReport rpt = new CityDetailsReport();
      rpt.setCityName(rP.getCityName());

      SimpleDateFormat dateFormat = new SimpleDateFormat("hh:mm");

      try {
         // scalars
         String sqlStatement = "SELECT country, airport, language, country_iso_code, "
               + " current_timestamp as run_date "
               + " from APP.CITIES"
               + " where city_name = ? ";

         PreparedStatement pstmt = dbConn.prepareStatement(sqlStatement);
         pstmt.setString(1, rP.getCityName());
         ResultSet rs = pstmt.executeQuery();

         if (rs.next()) {
            rpt.setRunDate(rs.getTimestamp("run_date"));
            rpt.setCountry(rs.getString("country"));
            rpt.setAirport(rs.getString("airport"));
            rpt.setLanguage(rs.getString("language"));
            rpt.setCountryISOCode(rs.getString("country_iso_code"));
         } else {
            throw new SQLException("No data found for city: "
                  + rP.getCityName());
         }

         rs.close();

         // arrivals
         sqlStatement = "SELECT flight_number, " + " origin, depart_time,"
               + " arrive_time, miles, number_of_segments, "
               + " aircraft_type " + " from APP.V_FLIGHTLIST "
               + " where destination_city = ? "
               + " order by arrive_time, flight_number ";

         System.out.println(sqlStatement);
         pstmt = dbConn.prepareStatement(sqlStatement);
         pstmt.setString(1, rP.getCityName());
         rs = pstmt.executeQuery();

         Arrivals arrs = new Arrivals();
         List<Arrivals.Arrival> arrList = arrs.getArrival();
         rpt.setArrivals(arrs);
         while (rs.next()) {
            Arrivals.Arrival item = new Arrivals.Arrival();
            item.setFlightNumber(rs.getString("flight_number"));
            item.setOrigin(rs.getString("origin"));
            try {
               item.setArriveTime(dateFormat.parse(rs.getString("arrive_time")));
            } catch (ParseException e) {
               e.printStackTrace();
            }
            try {
               item.setDepartTime(dateFormat.parse(rs.getString("depart_time")));
            } catch (ParseException e) {
               e.printStackTrace();
            }
            item.setMiles(rs.getInt("miles"));
            item.setNumberOfSegments(rs.getInt("number_of_segments"));
            item.setAircraftType(rs.getString("aircraft_type"));
            arrList.add(item);
         }

         pstmt.close();

         // departures
         sqlStatement = "SELECT flight_number, " + " destination, depart_time,"
               + " arrive_time, miles, number_of_segments, "
               + " aircraft_type " + " from APP.V_FLIGHTLIST "
               + " where origin_city = ? "
               + " order by depart_time, flight_number ";

         System.out.println(sqlStatement);
         pstmt = dbConn.prepareStatement(sqlStatement);
         pstmt.setString(1, rP.getCityName());
         rs = pstmt.executeQuery();

         Departures deps = new Departures();
         List<Departures.Departure> depList = deps.getDeparture();
         rpt.setDepartures(deps);
         while (rs.next()) {
            Departures.Departure item = new Departures.Departure();
            item.setFlightNumber(rs.getString("flight_number"));
            item.setDestination(rs.getString("destination"));
            try {
               item.setDepartTime(dateFormat.parse(rs.getString("depart_time")));
            } catch (ParseException e) {
               e.printStackTrace();
            }
            try {
               item.setArriveTime(dateFormat.parse(rs.getString("arrive_time")));
            } catch (ParseException e) {
               e.printStackTrace();
            }
            item.setMiles(rs.getInt("miles"));
            item.setNumberOfSegments(rs.getInt("number_of_segments"));
            item.setAircraftType(rs.getString("aircraft_type"));
            depList.add(item);
         }

         pstmt.close();

      } catch (SQLException e) {
         throw new SQLException("Exception in ReportSQL: " + e.getMessage());
      }

      JAXBElement<CityDetailsReport> jaxbElement = new JAXBElement<CityDetailsReport>(
            new QName("http://flightreports.googlecode.com/citydetails","CityDetailsReport"), 
            CityDetailsReport.class, rpt); 
      
//    Debug option: see marshalled XML object 
//    outputSourceXML(jaxbElement);
      return jaxbElement;
   }

}
